package com.winchain.chainbill.chain.service.impl;

import com.shell.bee.acct.transaction.po.AcctTxRec;
import com.shell.bee.acct.transaction.service.AcctTxRecService;
import com.shell.bee.base.utils.StringUtil;
import com.winchain.chainbill.chain.ChainCallbackService;
import com.winchain.chainbill.chain.callback.CallbackService;
import com.winchain.chainbill.chain.callback.service.RecAdjustmentService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("chainCallbackService")
public class ChainCallbackServiceImpl implements ChainCallbackService {
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private AcctTxRecService AcctTxRecService;
	@Autowired
	private RecAdjustmentService recAdjustmentService;
	private Map<String, CallbackService> serviceMap = new HashMap();

	public ChainCallbackServiceImpl(List<CallbackService> services) {
		for (CallbackService service : services) {
			this.serviceMap.put(service.getType(), service);
		}
	}

	public void callback(String txSn, String txSnHost) {
		List<AcctTxRec> txs = this.AcctTxRecService.selectByTxSn(txSn);
		for (AcctTxRec tx : txs) {
			CallbackService service = (CallbackService) this.serviceMap.get(tx.getTxType());
			if (service == null) {
				this.logger.warn("������" + tx.getTxType() + "������callback����");
				return;
			}
			if ("EX".equals(tx.getTxSts())) {
				if (StringUtil.notEmpty(txSnHost)) {
					tx.setTxSnHost(txSnHost);
					this.recAdjustmentService.adjustRec(tx);
				}
			} else if (StringUtil.notEmpty(txSnHost)) {
				tx.setTxSnHost(txSnHost);
				service.confirm(tx);
			} else {
				service.cancel(tx);
			}
		}
	}

	public void callback(AcctTxRec tx, String txSnHost) {
		CallbackService service = (CallbackService) this.serviceMap.get(tx.getTxType());
		if (service == null) {
			this.logger.warn("������" + tx.getTxType() + "������callback����");
			return;
		}
		if (StringUtil.notEmpty(txSnHost)) {
			tx.setTxSnHost(txSnHost);
			service.confirm(tx);
		} else {
			service.cancel(tx);
		}
	}
}
